package edu.dgut.bbssystem.filter;


import edu.dgut.bbssystem.common.ActionResult;
import edu.dgut.bbssystem.common.Constant;
import edu.dgut.bbssystem.pojo.User;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@WebFilter(urlPatterns = "/*", filterName = "authFilter")
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String id = request.getSession().getId();

        User user = new User();
        user.setUserName("admin");
        user.setPassword("admin");
        user.setUserId(999999999);
        //开发期间使用默认登录超级管理员
        if(needLogin(request)) {
            request.getSession().setAttribute("user",user);
        }
/*        if (needLogin(request)) {
            //返回没登录信息
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            ActionResult actionResult = new ActionResult(Constant.NOT_LOGIN, null);
            JSONObject jsonObject = JSONObject.fromObject(actionResult);
            response.getWriter().write(jsonObject.toString());
            return;
        }*/
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    /**
     * 判断是否需要登录
     * @param request
     * @return
     */
    private boolean needLogin(HttpServletRequest request) {
        Object user = request.getSession().getAttribute("user");
        return user==null?true:false;
    }
    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }
}
